import { ref,  onMounted } from 'vue'
import service from '@/utils/request'
import Auth from '@/components/mixin/auth.js'
import { ElNotification, ElMessageBox } from 'element-plus'

export default {
  name: "OrgManage",
  mixins: [Auth],
  setup() {

    const orgForm = ref(null)
    const dialogTitle = ref('新增机构')
    const initForm = {
      name: '',
      phone: '',
      remark: '',
      enable: 0,
      check: 1,
      img: '',
    }
    const formParam = ref(Object.assign({}, initForm))

    const phoneValid = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else if (!/^1\d{10}$/.test(value)) {
        callback(new Error('手机格式不合法!'));
      } else {
        callback();
      }
    }

    const rules = ref( {
      name: [
        { required: true, message: '请输入机构名称', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      phone: [
        { validator: phoneValid, required: true, trigger: 'change' }
      ], 
      enable: [
        { type: 'number', required: true, message: '请选择启用状态', trigger: 'change' }
      ],
      // check: [
      //   { type: 'number', required: true, message: '请选择审核状态', trigger: 'change' }
      // ],
      // img: [
      //   { required: true, message: '请上传营业执照', trigger: 'change' }
      // ],
    })
    const enableStatuss = {
      0: '未启用',
      1: '启用',
    }
    const checkStatuss = {
      0: '审核驳回',
      1: '审核中',
      2: '审核通过',
    }
    const listData = ref([])
    const refreshTable = async () => {
      listData.value = (await service.get('shipping/organization')).data
    }
    const dialogFormVisible = ref(false)

    const showImg = (event) => { 
      formParam.value.img = URL.createObjectURL(event.target.files[0])
      setTimeout(() => URL.revokeObjectURL(formParam.value.img), 0)
    }

    const addClickEvent = () => {
      dialogTitle.value = '新增机构'
      dialogFormVisible.value = true
      Object.assign(formParam.value, initForm)
    }

    let editRowId
    const editClickEvent = (row) => {
      editRowId = row.id
      dialogTitle.value = '修改机构'
      dialogFormVisible.value = true
      Object.keys(initForm).forEach(k => row[k] && (formParam.value[k] = row[k]))
    }

    const removeClickEvent = (id) => {
      ElMessageBox.confirm('确认删除机构？', 'Confirmation Information', {type: 'warning'}).then(async () => {
        await service.delete(`rental/organization/${id}`)
        // @ts-ignore
        ElNotification.success({title: 'Prompt information', message: '删除机构成功', position: 'bottom-right'})
        refreshTable()
      })

    }

    const resetForm = () => {
      // @ts-ignore
      orgForm.value.resetFields()
    }

    const submitForm = () => {
      // @ts-ignore
      orgForm.value.validate(async (valid) => {
        if (!valid) {
          // @ts-ignore
          ElNotification.warning({ title: 'Prompt information', message: 'Verification failed!', position: 'bottom-right' })
          return
        }

        const formData = new FormData()
        const uploadFile = document.querySelector('#upload-file')
        for (const [k, n] of Object.entries(formParam.value)) {
          // if (k == 'img') {
          //   // @ts-ignore
          //   uploadFile.files.length > 0 && formData.append(k, uploadFile.files[0])
          //   continue
          // }
          // @ts-ignore
          formData.append(k, n)
        }
        const isAdd = dialogTitle.value === '新增机构'
        await service[isAdd? 'post': 'put']('rental/organization' + (isAdd ? '': `/${editRowId}`), formData)
        // @ts-ignore
        ElNotification.success({ title: 'Prompt information', message: 'Successfully saved', position: 'bottom-right' })
        dialogFormVisible.value = false
        refreshTable()
      })
    }


    onMounted(() => refreshTable())

    return {
      rules,
      formParam,
      listData,
      dialogTitle,
      dialogFormVisible,
      enableStatuss,
      checkStatuss,
      showImg,
      orgForm,
      resetForm,
      submitForm,
      addClickEvent,
      editClickEvent,
      removeClickEvent,
    }
  }
}
